/**
 * 用户 vuex 模块
 * @author 杨世峰
 */

import { login } from '@/api/user/userBasicApi'
import { getToken, setToken, getUserId, setUserId, getRoleId, setRoleId, removeToken, removeUserId, removeRoleId } from '@/utils/auth'

const user = {
    state: {
        token: getToken(),
        userId: getUserId(),
        name: '',
        roleId: getRoleId(),
    },

    mutations: {
        SET_TOKEN: (state, token) => {
            state.token = token
        },
        SET_USERID: (state, userId) => {
            state.userId = userId
        },
        SET_NAME: (state, name) => {
            state.name = name
        },
        SET_ROLE: (state, roleId) => {
            state.roleId = roleId
        },
        REMOVE_TOKEN: (state) => {
            state.token = ''
        },
        REMOVE_USERID: (state) => {
            state.userId = ''
        },
        REMOVE_NAME: (state) => {
            state.name = ''
        },
        REMOVE_ROLE: (state) => {
            state.roleId = ''
        }
    },

    actions: {
        Login(context, userInfo) {
            return new Promise((resolve, reject) => {
                login(userInfo).then(res => {
                    // 返回 200+ http 报文的处理
                    if (res.resultCode == 200) {
                        setToken(res.data.token)
                        setUserId(res.data.userId)
                        setRoleId(res.data.roleId)
                        context.commit('SET_USERID', Number(res.data.userId))
                        context.commit('SET_TOKEN', res.data.token)
                        context.commit('SET_ROLE', Number(res.data.roleId))
                    } else {
                        alert(res.message)
                    }
                    resolve()
                }).catch(error => {
                    alert("error")
                    reject(error)
                })
            })
        },
        Logout(context) {
            removeToken()
            removeUserId()
            removeRoleId()
            context.commit('REMOVE_TOKEN')
            context.commit('REMOVE_USERID')
            context.commit('REMOVE_ROLE')
        }
    }
}

export default user